package com.hethongviet.job.pages;

import group.pals.android.lib.ui.filechooser.FileChooserActivity;
import group.pals.android.lib.ui.filechooser.io.LocalFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.hethongviet.job.AppMain;
import com.hethongviet.job.Config;
import com.hethongviet.job.R;
import com.hethongviet.job.helpers.CodeResult;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.helpers.database.CommentSQLite;
import com.hethongviet.job.helpers.download.DownloadFile;
import com.hethongviet.job.helpers.sound.SoundPlay;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class DetailCommentActivity extends Activity
{
	private Button _buttonAudioPlay = null;
	private Button _buttonAudioStop = null;
	private Button _buttonBack = null;
	private Button _buttonNext = null;
	private Button _buttonImage = null;
	private Button _buttonAttachmentDownload = null;

	private TextView _textCommenter = null;
	private TextView _textContent = null;
	private TextView _textDateCreated = null;
	private TextView _textWorker = null;
	private TextView _textImageStatus = null;
	private TextView _textAttachmentStatus = null;

	private FileInputStream _fileAudioInputStream = null;

	private Timer _timerStopAudio = new Timer();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		AppMain.prepareWindow(this);

		setContentView(R.layout.page_detail_comment);

		AppMain.showTaskTitle(this);

		_textCommenter = (TextView) findViewById(R.id.editTextViewCommentCommenter);

		_textContent = (TextView) findViewById(R.id.editTextViewCommentContent);

		_textDateCreated = (TextView) findViewById(R.id.editTextViewCommentDateCreate);

		_textWorker = (TextView) findViewById(R.id.editTextViewCommentWorker);

		_textImageStatus = (TextView) findViewById(R.id.textCommentImageStatus);

		_buttonBack = (Button) findViewById(R.id.buttonCommentBack);
		_buttonNext = (Button) findViewById(R.id.buttonCommentNext);

		_buttonImage = (Button) findViewById(R.id.buttonCommentImage);

		_textAttachmentStatus = (TextView) findViewById(R.id.textCommentAttachmentStatus);
		_buttonAttachmentDownload = (Button) findViewById(R.id.buttonCommentAttachmentDownload);
		_buttonAudioPlay = (Button) findViewById(R.id.buttonCommentAudioPlay);
		_buttonAudioStop = (Button) findViewById(R.id.buttonCommentAudioStop);

		showContent();

		if (AppMain._listComments.size() < 2)
		{
			((RelativeLayout) findViewById(R.id.layoutCommentDetailNextBack)).setVisibility(View.GONE);
		}

		else if (AppMain._currentIndexComment == 0)
		{
			_buttonBack.setVisibility(View.INVISIBLE);
		}

		_buttonBack.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				if (_timerStopAudio != null)
				{
					AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
					AppMain.callOnWindowFocusChange(DetailCommentActivity.this);
				}

				AppMain._currentIndexComment--;

				if (AppMain._currentIndexComment < 0)
					AppMain._currentIndexComment = 0;

				if (AppMain._currentIndexComment == 0)
				{
					_buttonBack.setVisibility(View.INVISIBLE);
				}

				if (AppMain._currentIndexComment == AppMain._listComments.size() - 2)
				{
					_buttonNext.setVisibility(View.VISIBLE);
				}
				showContent();
				updateRead();

				getWindow().getDecorView().invalidate();
			}
		});
		_buttonNext.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{

				if (_timerStopAudio != null)
				{
					AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
					AppMain.callOnWindowFocusChange(DetailCommentActivity.this);
				}
				AppMain._currentIndexComment++;
				if (AppMain._currentIndexComment >= AppMain._listComments.size())
					AppMain._currentIndexComment = AppMain._listComments.size() - 1;
				if (AppMain._currentIndexComment == AppMain._listComments.size() - 1)
				{
					_buttonNext.setVisibility(View.INVISIBLE);
				}
				if (AppMain._currentIndexComment == 1)
				{
					_buttonBack.setVisibility(View.VISIBLE);
				}
				showContent();
				updateRead();

				getWindow().getDecorView().invalidate();
			}
		});
	}

	private void updateRead()
	{
		if (Config.USE_COMMENT_MARK_UNREAD
				&& !AppMain.getCurrentComment().isRead())
		{
			AppMain.getCurrentComment().setRead(true);
			CommentSQLite commentSQLite = new CommentSQLite(DetailCommentActivity.this);
			commentSQLite.updateRead(AppMain.getCurrentComment());
		}
	}

	private void showContent()
	{
		_textCommenter.setText(AppMain.getCurrentComment().getSender());
		_textContent.setText(AppMain.getCurrentComment().getContent());
		_textDateCreated.setText(AppMain.getCurrentComment().getDateCreate());
		_textWorker.setText(AppMain.getCurrentTask().getWorker());

		if (AppMain.getCurrentComment().getFileImage() == null
				|| TextUtils.isEmpty(AppMain.getCurrentComment().getFileImage().getName()))
		{
			_textImageStatus.setVisibility(View.VISIBLE);
			_buttonImage.setVisibility(View.GONE);
		}
		else
		{
			_textImageStatus.setVisibility(View.GONE);
			_buttonImage.setOnClickListener(new OnClickListener()
			{
				public void onClick(View arg0)
				{
					AppMain._imageFileView = AppMain.getCurrentComment().getFileImage();
					Intent intent = new Intent(DetailCommentActivity.this,
							ViewImageActivity.class);
					intent.putExtra("request_type",
							AppMain.REQUEST_DOWNLOAD_IMAGE);
					startActivityForResult(intent, AppMain.REQUEST_VIEW_IMAGE);
				}
			});
			_buttonImage.setVisibility(View.VISIBLE);
		}

		if (AppMain.getCurrentComment().getFileAttachment() == null
				|| TextUtils.isEmpty(AppMain.getCurrentComment().getFileAttachment().getName()))
		{
			_textAttachmentStatus.setVisibility(View.VISIBLE);
			_buttonAttachmentDownload.setVisibility(View.GONE);
		}
		else
		{
			_textAttachmentStatus.setVisibility(View.GONE);
			_buttonAttachmentDownload.setOnClickListener(new OnClickListener()
			{
				public void onClick(View arg0)
				{
					AppMain.showFileChooser(DetailCommentActivity.this,
							AppMain.REQUEST_CHOOSE_DIRECTORY);
				}
			});
			_buttonAttachmentDownload.setVisibility(View.VISIBLE);
		}

		String audioName = AppMain.getCurrentComment().getFileAudio().getName();
		if (!TextUtils.isEmpty(audioName))
		{
			_buttonAudioPlay.setVisibility(View.VISIBLE);
			_buttonAudioPlay.setOnClickListener(new OnClickListener()
			{

				public void onClick(View arg0)
				{
					if (!AppMain.isSdCardPresent())
					{
						AppMain.showAlert(DetailCommentActivity.this,
								R.string.textErrorSDCardNotAvailable, false);
						return;
					}
					File directory = new File(
							Environment.getExternalStorageDirectory()
									+ AppMain.DIRECTORY_AUDIO_FILE);
					
					showDialog(AppMain.DIALOG_DOWNLOAD_PROGRESS);
					
					AppMain.downloadAndSave(
							DetailCommentActivity.this,
							_progressDialog,
							ServiceHelper.URL_DOWNLOAD_AUDIO,
							directory.getAbsolutePath(),
							AppMain.getCurrentComment().getFileAudio().getName());

					AppMain.getCurrentComment().getFileAudio().setPath(
							directory.getAbsolutePath());

				}
			});

			_buttonAudioStop.setOnClickListener(new OnClickListener()
			{

				public void onClick(View arg0)
				{
					AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
					AppMain.callOnWindowFocusChange(DetailCommentActivity.this);
					return;
				}
			});
		}
		else
		{
			_buttonAudioPlay.setVisibility(View.GONE);
			_buttonAudioStop.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_option_comment_detail, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menuItemSkype)
		{
			AppMain.startSkype(this);
		}
		else if (item.getItemId() == R.id.menuItemAcount)
		{
			AppMain.showDialogList(this, AppMain.DIALOG_ACCOUNT);
		}
		return true;
	}

	private ProgressDialog _progressDialog = null;

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
			case AppMain.DIALOG_DOWNLOAD_PROGRESS:
				_progressDialog = new ProgressDialog(this);
				_progressDialog.setMessage(getString(R.string.textMessageDownloadFile));
				_progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				_progressDialog.setCancelable(true);
				_progressDialog.show();
				return _progressDialog;
			default:
				return null;
		}
	}

	@TargetApi(5)
	@Override
	public void onBackPressed()
	{
		System.gc();
		super.onBackPressed();
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		switch (DownloadFile._errorCode)
		{
			case DownloadFile.ERROR_CONNECTION:
				AppMain.showAlert(this, R.string.textErrorNetwork, false);
				break;
			case DownloadFile.ERROR_URL_NOT_EXIST:
				AppMain.showAlert(this, R.string.textErrorURLNotExist, false);
				break;

			case DownloadFile.ERROR_FILE_CREATE:
				AppMain.showAlert(this, R.string.textErrorFileNotCreated, false);
				break;
			case DownloadFile.STATUS_SUCCESS:
				if (AppMain._downloadType.equalsIgnoreCase(ServiceHelper.URL_DOWNLOAD_AUDIO))
				{
					try
					{
						_fileAudioInputStream = new FileInputStream(
								AppMain.getCurrentComment().getFileAudio().getPath()
										+ "/"
										+ AppMain.getCurrentComment().getFileAudio().getName());
					} catch (FileNotFoundException e1)
					{
						e1.printStackTrace();
					}

					if (_fileAudioInputStream == null)
					{
						AppMain._codeResultService = CodeResult.FAIL_AUDIO_LOAD;
						AppMain.callOnWindowFocusChange(DetailCommentActivity.this);
						return;
					}

					/* Play audio */
					try
					{

						int duration = SoundPlay.play(_fileAudioInputStream.getFD());

						TimerTask timerTask = new TimerTask()
						{
							@Override
							public void run()
							{
								AppMain._codeResultService = CodeResult.STOP_PLAY_AUDIO;
								AppMain.callOnWindowFocusChange(DetailCommentActivity.this);
								return;
							}
						};

						_timerStopAudio = new Timer();
						_timerStopAudio.schedule(timerTask, duration);

					} catch (Exception e)
					{
						// AppMain._codeResultService =
						// CodeResult.FAIL_PLAY_AUDIO;
						// AppMain.callOnWindowFocusChange(DetailCommentActivity.this);
						e.printStackTrace();
						break;
					}

					_buttonAudioPlay.setVisibility(View.GONE);

					_buttonAudioStop.setVisibility(View.VISIBLE);
				}
				else
				{
					AppMain.showAlert(
							this,
							getString(R.string.textMessageDownloadFileSuccess)
									+ ": "
									+ AppMain.getCurrentComment().getFileAttachment().getPath()
									+ "/"
									+ AppMain.getCurrentComment().getFileAttachment().getName(),
							false);
				}
				break;
			default:
				break;
		}
		DownloadFile._errorCode = DownloadFile.STATUS_NONE;

		switch (AppMain._codeResultService)
		{
			case FAIL_AUDIO_LOAD:
				AppMain.showAlert(this, R.string.textErrorFailLoadAudio, false);
				break;
			case STOP_PLAY_AUDIO:
				_timerStopAudio.cancel();
				/* Stop play video */
				SoundPlay.stop();

				try
				{
					_buttonAudioStop.setVisibility(View.GONE);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				try
				{
					_buttonAudioPlay.setVisibility(View.VISIBLE);
				} catch (Exception e)
				{
					e.printStackTrace();
				}

				break;

			default:
				break;
		}

		AppMain._codeResultService = CodeResult.NONE;

		super.onWindowFocusChanged(hasFocus);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case AppMain.REQUEST_VIEW_IMAGE:
				AppMain._imageFileView = null;
				System.gc();
				break;

			case AppMain.REQUEST_CHOOSE_DIRECTORY:
				if (resultCode == RESULT_OK)
				{
					@SuppressWarnings("unchecked")
					List<LocalFile> localFiles = (List<LocalFile>) data.getSerializableExtra(FileChooserActivity.Results);
					File directory = localFiles.get(0);
					showDialog(AppMain.DIALOG_DOWNLOAD_PROGRESS);
					AppMain.downloadAndSave(
							this,
							_progressDialog,
							ServiceHelper.URL_DOWNLOAD_FILE,
							directory.getAbsolutePath(),
							AppMain.getCurrentComment().getFileAttachment().getName());
					AppMain.getCurrentComment().getFileAttachment().setPath(
							directory.getAbsolutePath());
				}
				break;
			default:
				break;
		}
	}

	@Override
	protected void onDestroy()
	{
		if (Config.USE_AUDIO_RECORD)
		{
			SoundPlay.stop();
		}
		AppMain.hideAllDialog();
		super.onDestroy();
	}

}
